from datetime import datetime

from django.conf import settings
from django.contrib.auth.models import User, Group
from django.contrib.sites.models import Site
from django.db import models
from django.db.models import signals
from django.utils.translation import ugettext_lazy as _

from popboard.managers import PostManager, LivePostManager, ThreadManager, LiveCategoryManager 


class Category(models.Model):
    """
    ``Category`` - A Forum Category
    """
    site = models.ForeignKey(Site)
    created = models.DateTimeField(_("Created"), default=datetime.now)
    name = models.CharField(_("Label"), max_length=32)
    slug = models.SlugField(_("Slug"))
    description = models.TextField(_("Description"))
    recent_post = models.ForeignKey('Post', null=True, blank=True)

    objects = models.Manager()
    live_objects = LiveCategoryManager()
    
    def save(self, force_insert=False, force_update=False):
        return super(Category, self).save(force_insert, force_update)

    def __unicode__(self):
        return self.name

    class Meta:
        verbose_name_plural = 'categories'

    def get_absolute_url(self):
        return ('popboard-thread-category-index', [], {"cat_id": str(self.id)})
    get_absolute_url = models.permalink(get_absolute_url)


class Moderator(models.Model):
    """
    ``Moderator`` - Moderators are users which 
    have access to admin functions for defined categories
    """
    site = models.ForeignKey(Site)
    category = models.ManyToManyField(Category)
    user = models.ForeignKey(User)
    
    def save(self, force_insert=False, force_update=False):
        if not self.site:
            self.site = Site.objects.get_current()
        super(Moderator, self).save(force_insert, force_update)
        
    
    def __unicode__(self):
        return u"%s moderator of %s" % (self.user.username, self.category.name)


class Thread(models.Model):
    """
    ``Thread`` - A Thread
    """
    created = models.DateTimeField(_("Created"), auto_now_add=True)
    modified = models.DateTimeField(_("Original Date"), editable=False, default=datetime.now)
    
    site = models.ForeignKey(Site)
    category = models.ForeignKey(Category)
    
    title = models.CharField(_("Title"), max_length=255)
    sticky = models.BooleanField(_("Sticky"), default=False)
    first_post = models.ForeignKey('Post', related_name='thread_firstpost', 
                                    null=True, blank=True, editable=False)
    user = models.ForeignKey(User)

    closed = models.BooleanField(_("Thread Closed"), default=False)

    last_post = models.ForeignKey('Post' , related_name='thread_lastpost', 
                                 null=True, blank=True, editable=False)
    hits = models.PositiveIntegerField(_("Hit Count"), default=1)
    post_count = models.PositiveIntegerField(_("Post Count"), default=1)
    last_active = models.DateTimeField(_("Last Active Date"), default=datetime.now)

    objects = models.Manager()
    live_objects = ThreadManager()

    class Meta:
        get_latest_by = ('post__created',)

    def __unicode__(self):
        return self.title
    
    def get_absolute_url(self):
        return ("popboard-thread", [], {"thread_id": str(self.id)})
    get_absolute_url = models.permalink(get_absolute_url)


class Post(models.Model):
    """
    ``Post`` - A User Post
    """
    site = models.ForeignKey(Site)
    created = models.DateTimeField(_("Created"), editable=False, auto_now_add=True)
    modified = models.DateTimeField(_("Modified"), editable=False, default=datetime.now)
    user = models.ForeignKey(User, editable=False, blank=True)
    thread = models.ForeignKey(Thread)
    ip = models.IPAddressField(_("IP Address"), blank=True)

    body_raw = models.TextField(_("Body"))
    body = models.TextField(_("Body (formatted)"))
    
    censor = models.BooleanField(_("Censor"), default=False) # moderator level access

    objects = PostManager() 
    live_objects = LivePostManager()
        
    def save(self, force_insert=False, force_update=False):
        self.modified = datetime.now()
        from markdown import Markdown
        md = Markdown()
        self.body = md.convert(self.body_raw)
        return super(Post, self).save(force_insert, force_update)

    class Meta:
        ordering = ("created",)

    def get_absolute_url(self):
        return ("popboard-thread", [], {"thread_id": str(self.thread.id)})
    get_absolute_url = models.permalink(get_absolute_url)

    def __unicode__(self):
        return '%s on %s' % (self.user.username, self.created,)


class AbuseReport(models.Model):
    """
    ``AbuseReport`` - Allow a user to report abuse
    """
    post = models.ForeignKey(Post)
    submitter = models.ForeignKey(User)

    class Meta:
        unique_together = (('post', 'submitter'),)


class WatchList(models.Model):
    """
    ``WatchList`` - Allow a user to watch a thread
    """
    user = models.ForeignKey(User)
    thread = models.ForeignKey(Thread)

PROFILE_DISPLAY_CHOICES = ((5, '5'), (10, '10'), (20, '20'), (50, '50'))

class ForumProfile(models.Model):
    '''
    ``ForumProfile`` - A users forum preferences
    '''
    user = models.ForeignKey(User, unique=True)
    profile = models.TextField(_("Profile"), blank=True)
    ppp = models.IntegerField(_("Posts Per Page"),
                              choices=PROFILE_DISPLAY_CHOICES,
                              default=20)
    tpp = models.IntegerField(_("Threads Per Page"),
                             choices=PROFILE_DISPLAY_CHOICES,
                             default=20)
    email_notifications = models.BooleanField(_("Email Notifications"), default=False, blank=True,
                                             help_text="Email notifications for watched discussions.")